package com.jielihaofeng.springboot.shorturl.controller;


import com.jielihaofeng.springboot.shorturl.common.Result;
import com.jielihaofeng.springboot.shorturl.constant.UrlConstants;
import com.jielihaofeng.springboot.shorturl.entity.ShortUrlVo;
import com.jielihaofeng.springboot.shorturl.service.ShortUrlService;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Johnnie Wind
 * @since 2021-06-03
 */
@Api
@RestController
@RequestMapping("/shortUrl")
public class ShortUrlController {

    @Autowired
    ShortUrlService shortUrlService;

    @GetMapping
    public Result getShortUrl(@RequestParam String url){

        if (StringUtils.isBlank(url)){
            return new Result().fail("url为空!");
        }

        if (!url.startsWith("http://") && !url.startsWith("https://")){
            return new Result().fail("url必须以http或https开头!");
        }

        // 获取对应短链
        String shortUrl = shortUrlService.getShortUrl(url);
        ShortUrlVo shortUrlVo = new ShortUrlVo();
        shortUrlVo.setShortUrl(shortUrl);
        shortUrlVo.setUrl(url);
        return new Result<ShortUrlVo>().data(shortUrlVo);
    }

    @PutMapping
    public Result updateShortUrl(@RequestParam String url){

        if (StringUtils.isBlank(url)){
            return new Result().fail("url为空!");
        }

        if (!url.startsWith("http://")||!url.startsWith("https://")){
            return new Result().fail("url必须以http或https开头!");
        }

        // 获取对应短链
        String shortUrl = shortUrlService.updateShortUrl(url);
        if (StringUtils.isBlank(shortUrl)){
            return new Result().fail("系统不存在此链接的短链，请先获取！");
        }

        ShortUrlVo shortUrlVo = new ShortUrlVo();
        shortUrlVo.setShortUrl(shortUrl);
        shortUrlVo.setUrl(url);
        return new Result<ShortUrlVo>().data(shortUrlVo);
    }

}

